package com.example.demo.common;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Convert {
    //将字符串转换成日期型，格式：yyyy-MM-dd
    public static Date toDate(String strDate) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd").parse(strDate);
    }

    //将字符串转换成时间型，格式：yyyy-MM-dd HH:mm:ss
    public static Date toTime(String strTime) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(strTime);
    }

    //将日期转换成字符串型，格式：yyyy-MM-dd
    public static String toString(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    //将字符串转换成 Decimal 格式含两位小数，四舍五入
    public static BigDecimal toDecimal(String StrBd) {
        try {
            return new BigDecimal(StrBd).setScale(2, BigDecimal.ROUND_HALF_UP);
        } catch (Exception ex) {
            return null;
        }
    }

    public static JSONObject mapStringToJson(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        JSONObject js = new JSONObject();
        for (String string : strs) {
            String key = string.split("=")[0];
            String value = string.split("=")[1];
            js.put(key.trim(), value.trim());
        }
        return js;
    }

    // 将上传文件转成Base64码
    public static String fileToBase64(MultipartFile file) {
        String contentType = file.getContentType();
        byte[] bytes = null;
        String base64 = null;
        try {
            bytes = file.getBytes();
            base64 = "data:" + contentType + ";base64," + new BASE64Encoder().encode(bytes);
            base64 = base64.replaceAll("[\\s*\t\n\r]", "");
            bytes.clone();
        }
        catch (Exception ex) {
            if (bytes != null) {
                bytes.clone();
            }
        }

        return base64;
    }

    // 将路径文件转成Base64码
    public static String fileToBase64(String url) {
        FileInputStream fis = null;
        byte[] bytes = null;
        String base64 = null;
        try {
            File file = new File(url);
            fis = new FileInputStream(file);
            bytes = new byte[fis.available()];
            fis.read(bytes);
            base64 = new BASE64Encoder().encode(bytes);
            base64 = base64.replaceAll("[\\s*\t\n\r]", "");
            fis.close();
            bytes.clone();
        }
        catch (Exception ex) {
            if (fis != null) {
                try {
                    fis.close();
                }
                catch (Exception ignored) { }
            }
            if (bytes != null) {
                bytes.clone();
            }
        }

        return base64;
    }
}
